package com.bdc.memory.service.impl;

import com.bdc.BdcVar;
import com.bdc.memory.dao.IRecordDao;
import com.bdc.memory.dao.ITagDao;
import com.bdc.memory.domain.RecordInfo;
import com.bdc.memory.domain.TagInfo;
import com.bdc.memory.service.IRecordService;
import com.bdc.memory.service.ITagService;
import com.bdc.utils.BdcUtils;
import com.bdc.utils.TokenUtils;
import com.google.inject.Inject;
import com.google.inject.persist.Transactional;

import java.util.List;

/**
 * User: Shawn
 * Date: 2011-6-20
 * Time: 17:38:45
 */
public class ITagServiceImpl implements ITagService {

    @Inject
    private ITagDao tagDao;
    @Inject
    private IRecordDao recordDao;
    @Inject
    private IRecordService recordService;

    @Transactional
    public long addTag(long userId, String tag) {
        TagInfo tagInfo = new TagInfo(userId, tag);
        tagDao.addTag(tagInfo);
        return tagInfo.getTagId();
    }

    @Transactional
    public void updateTag(long userId, long tagId, String tag) {
        TagInfo tagInfo = tagDao.getTag(tagId);
        String oldTag = tagInfo.getTag();

        List<RecordInfo> recordList = recordDao.getRecordList(userId, oldTag);
        for (RecordInfo record : recordList) {
            String newTagString = tag;

            String[] tagArray = TokenUtils.getStringArray(record.getTag(), BdcVar.TAG_SEPERATOR);
            for (String t : tagArray) {
                if (t.equals(oldTag)) continue;
                newTagString += BdcVar.TAG_SEPERATOR + t;
            }

            newTagString = BdcUtils.filterTagString(newTagString);
            record.setTag(newTagString);
        }

        tagInfo.setTag(tag);
    }

    @Transactional
    public void delTag(long tagId) {
        TagInfo tagInfo = tagDao.getTag(tagId);

        List<RecordInfo> recordList = recordDao.getRecordList(tagInfo.getUserId(), tagInfo.getTag());
        for (RecordInfo info : recordList) {
            recordService.delRecord(info.getRecordId());
        }
        tagDao.delTag(tagId);
    }

    public List<TagInfo> getTagList(long userId) {
        return tagDao.getTagList(userId);
    }
}
